﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.IO;
using Microsoft.TeamFoundation.VersionControl.Common;
using Microsoft.TeamFoundation.Build.Client;

namespace BDV.TfsCustomActivities.BuildTasks
{
    /// <summary>
    /// Do a complete checkin on the workspace
    /// Effectue un Check In sur l'entierete d'un Workspace
    /// </summary>
    [BuildActivity(HostEnvironmentOption.All)]
    public sealed class CheckinWorkSpace : CodeActivity
    {
        /// <summary>
        /// Workspace concerned
        /// </summary>
        [RequiredArgument]
        public InArgument<Workspace> WorkSpace { get; set; }

        /// <summary>
        /// Comment to inject on the checkin
        /// </summary>
        [RequiredArgument]
        public InArgument<string> Comments { get; set; }

        /// <summary>
        /// Changeset id provided
        /// </summary>
        [RequiredArgument]
        public InArgument<string> ChangeSetId { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // Obtain the runtime value of the Text input argument
            Workspace workSpace = context.GetValue(this.WorkSpace);
            string comments = context.GetValue(this.Comments);
            string changesetId = context.GetValue(this.ChangeSetId);

            var pendings = workSpace.GetPendingChanges();

            if (pendings != null && pendings.Any())
                workSpace.CheckIn(
                    pendings
                    , "Build Agent"
                    , String.Format("<{0}> <changeset {2} > < {1} >", comments, RepositoryConstants.NoCICheckInComment, changesetId)
                    , null
                    , null
                    , new PolicyOverrideInfo("Auto CheckIn", null)
                    , CheckinOptions.SuppressEvent);
        }
    }
}
